#!/bin/python

# VIDEO BUDDHA 2 - logging
# --------------------------------------
# For easier sharing of logging objects and
# files.
# --------------------------------------

import ConfigParser
import time

class Logger:

	def __init__(self):
		self.file = None
		self.level = ['INFO', 'WARNING', 'ERROR', 'CRITICAL', 'EXCEPTION']
		self.log_file = 'logs/log_' + str(int(time.time())) + '.log'
		
		self.config = ConfigParser.RawConfigParser()
		self.config.read('config.cfg')		
		
		self.create_log()		

	def create_log(self):
		try:
			if self.config.getboolean('main', 'b_log'):
				log = open(self.log_file, 'w')
				self.log("Log file created: " + self.log_file, self.level[0])
				log.close()
		except IOError as (errno, strerror):
			print "I/O error({0}): {1}".format(errno, strerror)
		except:
			print "Unexpected error while creating the log file"
			raise

	def log(self, msg, level):
		# Open and append the log file
		try:
			if self.config.getboolean('main', 'b_log'):
				log = open(self.log_file, 'a')
				log.write(time.strftime("%Y-%m-%d %H:%M:%S") + " (" + level + ") \t" + msg + "\n")
				log.close()
		except IOError as (errno, strerror):
			print "I/O error({0}): {1}".format(errno, strerror)
		except:
			print "Unexpected error:", sys.exc_info()[0]
			raise		